package com.ben.multiple.util;

import java.util.regex.Pattern;

/**
 * 去除特殊字符
 *
 * @author BenJin Yin
 * @date 2019/10/24
 */
public final class XssStripUtil {
    private XssStripUtil() {
    }

    private static final Pattern SCRIPT_PATTERN =
            Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE);

    private static final Pattern SRC_PATTERN = Pattern.compile("src[\r\n]*=",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);

    private static final Pattern END_SCRIPT_PATTERN = Pattern.compile("</script>", Pattern.CASE_INSENSITIVE);

    private static final Pattern START_SCRIPT_PATTERN = Pattern.compile("<script(.*?)>",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);

    private static final Pattern JAVASCRIPT_PATTERN = Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE);

    private static final Pattern EVAL_PATTERN = Pattern.compile("eval\\((.*?)\\)",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);

    private static final Pattern EXPRESSION_PATTERN = Pattern.compile("e­xpression\\((.*?)\\)",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);

    private static final Pattern VB_SCRIPT_PATTERN = Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE);

    private static final Pattern ONLOAD_PATTERN = Pattern.compile("onload(.*?)=",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);

    /**
     * 使用正则表达式处理 XSS
     *
     * @param value String
     * @return String
     */
    public static String stripByRegex(String value) {
        if (value == null) {
            return null;
        }
        value = SCRIPT_PATTERN.matcher(value).replaceAll("");
        value = SRC_PATTERN.matcher(value).replaceAll("");
        value = END_SCRIPT_PATTERN.matcher(value).replaceAll("");
        value = START_SCRIPT_PATTERN.matcher(value).replaceAll("");
        value = JAVASCRIPT_PATTERN.matcher(value).replaceAll("");
        return value;
    }
}
